package features.advance.leetcode.interview.offer.easy;

import features.advance.leetcode.Solution;
import features.advance.leetcode.geometry.doublepointer.easy.ListNode;
import features.advance.leetcode.util.TreeUtil;

import java.util.Arrays;
import java.util.Stack;

/**
 *
 *  剑指 Offer 06. 从尾到头打印链表
 *  难度：简单
 *
 * 输入一个链表的头节点，从尾到头反过来返回每个节点的值（用数组返回）。
 *
 *
 *
 * 示例 1：
 *
 * 输入：head = [1,3,2]
 * 输出：[2,3,1]
 *
 *
 * 限制：
 *
 * 0 <= 链表长度 <= 10000
 *
 * @author LIN
 * @date 2021-05-06
 */
public class Offer06 extends Solution {

    public int[] reversePrint(ListNode head) {
        ListNode curr = head;
        Stack<Integer> s = new Stack();
        while(curr != null){
            s.push(curr.val);
            curr = curr.next;
        }
        int[] ret = new int[s.size()];
        for(int i=0;i<ret.length;i++){
            ret[i] = s.pop();
        }
        return ret;
    }


    public static void main(String[] args) {
        String str = "[1,3,2]";
        ListNode listNode = TreeUtil.parseLinkedList(str);
        Offer06 offer06 = new Offer06() {
            @Override
            public int[] reversePrint(ListNode head) {
                int count=0;
                ListNode node = head;
                while(node!=null){
                    node=node.next;
                    count++;
                }
                int[] res =new int[count];
                while(head!=null){
                    res[--count]=head.val;
                    head=head.next;
                }
                return res;
            }
        };

        int[] ints = offer06.reversePrint(listNode);
        System.out.println(Arrays.toString(ints));
    }
}
